import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { $gc } from 'gc-starter-ui-plus'
import qs from 'qs'
// RouterTab 内置路由
import { RouterTabRoutes } from 'vue-router-tab'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/todo', '/sys/cas', '/forgotPwd'] // 白名单

/* Layout */
import Layout from '@/layout/Index'
import LayoutMultiMenu from '@/layout/IndexMenu'
import LayoutTop from '@/layout/LayoutTop'
import LayoutEmpty from '@/layout/LayoutEmpty'

router.beforeEach(async(to, from, next) => {
  if (to.query.token !== undefined) {
    // 单点登录
    $gc.setToken(to.query.token)
  }
  await store.dispatch('core/initializeTheme')
  // 跳转进度条【开始】
  NProgress.start()
  // 首页重定向
  if (to.path === '/' && to.name !== 'home') {
    next({ name: 'home' })
    return
  }
  // 设置网页标题
  document.title = $gc.getPageTitle(to.meta.title)
  // iframe 页面刷新时会匹配 /iframe/:src/:title 路由
  if (to.matched && to.matched.length > 0) {
    for (let i = 0; i < to.matched.length; i++) {
      const matchedRoute = to.matched[i]
      if (matchedRoute.path.indexOf('/iframe/:src/:title') !== -1) {
        // 说明是通过本系统直接访问iframe的
        const iframeMenu = $gc.getIframeMenu(to.params.src, to.params.title)
        if (iframeMenu) {
          store.dispatch('core/updateCurrentRootMenuId', iframeMenu.rootId)
          store.dispatch('core/updateCurrentMenuId', iframeMenu.id)
        } else {
          console.error('该地址未授权，本系统无法查询，不要直接访问iframe地址，通过菜单path去访问')
        }
      }
    }
  }
  if (to.meta && to.meta.id) {
    // 打开的是动态创建的菜单路由，包含iframe路由和普通vue路由
    store.dispatch('core/updateCurrentRootMenuId', to.meta.rootId)
    store.dispatch('core/updateCurrentMenuId', to.meta.id)
  }
  if (to.meta && to.meta.extendObj && to.meta.extendObj.iframeUrl) {
    // 打开的是iframe路由
    let url = $gc.getIframeKey(to.meta.extendObj.iframeUrl)
    let query = {}
    if (to.name === 'home') {
      // 解决首页自动跳转配置参数丢失问题
      const menu = store.state.core.menuMap[to.meta.id]
      const menuQuery = $gc.fillMenuParams(menu)
      // 参数合并
      query = Object.assign(query, menuQuery, to.query)
    } else {
      query = to.query
    }
    const params = qs.stringify(query)
    if (params) {
      url = url + '?' + params
    }
    const path = `/iframe/${encodeURIComponent(url)}` + '/' + to.meta.title + '/'
    NProgress.done()
    next(path)
    return
  }
  const token = $gc.getToken()
  if (token) {
    if (to.path === '/login') {
      next('/')
      return
    }
    // 是否动态生成路由
    const dynamicCreateRoute = store.state.core.dynamicCreateRoute
    if (!dynamicCreateRoute) {
      try {
        // 获取用户信息
        await store.dispatch('user/getInfo')
        await store.dispatch('user/getRouters').then((data) => {
          store.dispatch('core/updateDynamicCreateRoute', true)
          if (data && data.length) {
            // 版本兼容处理
            $gc.versionCompat(data)
            // 存储按钮权限
            $gc.restorePermission(data)
            // 删除按钮权限
            data = $gc.deleteButtonMenu(data)
            // 平铺菜单集合转为树状、并存储
            $gc.restoreMenuList(data)
            let LayoutIndex
            const layoutType = $gc.$cookie.get('type') === null ? window.SITE_CONFIG.layoutType : $gc.$cookie.get('type')
            if (layoutType === 'layout-multimenu') {
              LayoutIndex = LayoutMultiMenu
            } else {
              LayoutIndex = Layout
            }
            const routeList = $gc.menu2route(data, {
              index: LayoutIndex,
              top: LayoutTop,
              empty: LayoutEmpty
            }, RouterTabRoutes)
            router.options.routes = [...routeList, ...[{ path: '*', redirect: '/404', hidden: true }]]
            router.addRoutes(router.options.routes)
            // 标示已经动态创建了路由
            next({ ...to, replace: true })
          } else {
            next(`/403`)
          }
        })
      } catch (error) {
        // 清除 token
        await store.dispatch('user/resetToken')
        next(`/login?redirect=${to.path}`)
      }
    } else {
      next()
    }
  } else {
    // 未登录
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (window.SITE_CONFIG['cas'].enable) {
        window.location.href = window.SITE_CONFIG['cas'].loginUrl
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  // 跳转进度条【完成】
  NProgress.done()
})
